package com.cjst.controller.sys;


import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cjst.controller.base.BaseController;
import com.cjst.pojo.sys.SysDept;
import com.cjst.pojo.sys.SysOffice;
import com.cjst.pojo.sys.SysRole;
import com.cjst.pojo.sys.SysUser;
import com.cjst.sdp.util.MapUtils;
import com.cjst.sdp.util.ShiroKit;
import com.cjst.sdp.util.ZTreeNode;
import com.cjst.service.sys.SysDeptService;
import com.cjst.service.sys.SysOfficeService;
import com.cjst.service.sys.SysRoleService;
import com.cjst.service.sys.SysUserService;
import com.cjst.sql.C;
import com.cjst.sql.Method;
import com.cjst.sql.WherePrams;
import com.cjst.util.CloneClass;
import com.cjst.util.code.PageUtil;
import com.cjst.util.common.DateUtil;
import com.cjst.util.json.ResultObj;

/**
 * 后台用户
 *
 * @author yj
 */
@Controller
@RequestMapping("/sys/sysUser")
public class SysUserController extends BaseController {

    private static final Logger log = Logger.getLogger(SysUserController.class);
    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private SysOfficeService officeService;

    @Autowired
    private SysUserService userService;


    @Autowired
    private SysRoleService roleService;

    /**
     * 查询数据
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(SysUser user) {
        WherePrams wherePrams = Method.where("status", C.EQ, "1");
        if (StringUtils.isNotEmpty(user.getName())) {
            wherePrams.and("name", C.LIKE, user.getName(), "1");
            wherePrams.or("userName", C.LIKE, user.getName(), "1");
            wherePrams.or("phone", C.LIKE, user.getName(), "1");
        }
        if (StringUtils.isNotEmpty(user.getCreateDate()) && StringUtils
            .isNotEmpty(user.getUpdateDate())) {
            wherePrams.and("createDate", C.DAEQ, user.getCreateDate());
            wherePrams.and("createDate", C.IXAOEQ, user.getUpdateDate());
        }
        if (StringUtils.isNotEmpty(user.getDeptId())) {
            WherePrams where = Method.where("status", C.EQ, "1");
            where.and("id", C.EQ, user.getDeptId(), "1");
            where.or("pids", C.LIKE, user.getDeptId(), "1");
            List<SysDept> depts = sysDeptService.list(where);
            String deptIds = "";
            for (int i = 0; i < depts.size(); i++) {
                deptIds += "'";
                deptIds += depts.get(i).getId();
                deptIds += "'";
                if (i < depts.size() - 1) {
                    deptIds += ",";
                }
            }
            if (!"".equals(deptIds)) {
                wherePrams.and("deptId", C.IN, deptIds);
            }
        }
        PageUtil<SysUser> pageUtil = userService.listPageCount(wherePrams);
        List<SysUser> users = pageUtil.getData();
        List<Map<String, Object>> maps = new ArrayList<>();
        for (SysUser sysUser : users) {
            Map<String, Object> userMap = MapUtils.transBean2Map(sysUser);
            String roleid = sysUser.getRoleId();
            if (StringUtils.isNotBlank(roleid)) {
                //WherePrams role_where = Method.where("id", C.EQ, roleid);
                SysRole role = roleService.get(roleid);
                if (role != null) {
                    userMap.put("roleName", role.getName());
                } else {
                    userMap.put("roleName", "-");
                }
            }
            String officeId = sysUser.getOfficeId();
            if (StringUtils.isNotEmpty(officeId)) {
                SysOffice office = officeService.get(officeId);
                if (null != office) {
                    userMap.put("officeName", office.getName());
                } else {
                    userMap.put("officeName", "-");
                }
            } else {
                userMap.put("officeName", "-");
            }
            maps.add(userMap);
        }

        PageUtil<Map<String, Object>> pages = new PageUtil<>();

        CloneClass.getClone(pageUtil, pages);
        pages.setData(maps);
        return this.packForBT(pages);
    }

    /**
     * 请求角色数据
     */
    @RequestMapping(value = "/getRoleData", method = RequestMethod.POST)
    @ResponseBody
    public Object getRoleData() {
        WherePrams wherePrams = Method.where("delFlag", C.EQ, "0");
        List<SysRole> roles = roleService.list(wherePrams);
        return roles;
    }

    /**
     * 系统用户列表页面
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @RequiresPermissions("user")//权限管理;
    public String toUser() {
        return "system/user/user";
    }

    /**
     * 跳转到添加页面
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    @RequiresPermissions("user_add")
    public String addUser() {
        return "system/user/user_add";
    }


    /**
     * 跳转到修改页面
     */
    @RequestMapping(value = "/update/{userId}", method = RequestMethod.GET)
    @RequiresPermissions("user_edit")
    public String updateUser(@PathVariable String userId, Model model) {
        WherePrams where = Method.where("id", C.EQ, userId);
        SysUser user = userService.get(where);
        if (user != null) {
            Map<String, Object> userMap = MapUtils.transBean2Map(user);
            String roleid = user.getRoleId();
            if (StringUtils.isNotBlank(roleid)) {
                //WherePrams role_where = Method.where("id", C.EQ, roleid);
                SysRole role = roleService.get(roleid);
                if (role != null) {
                    userMap.put("roleName", role.getName());
                } else {
                    userMap.put("roleName", "-");
                }
            }
            String officeId = user.getOfficeId();
            if (StringUtils.isNotEmpty(officeId)) {
                SysOffice office = officeService.get(officeId);
                if (null != office) {
                    userMap.put("officeName", office.getName());
                } else {
                    userMap.put("officeName", "-");
                }
            } else {
                userMap.put("officeName", "-");
            }
            String birthday = user.getBirthday();
            if (birthday != null) {
                String birth = DateUtil
                    .dateFormatToString(DateUtil.stringToDate(birthday), "yyyy-MM-dd");
                userMap.put("birthday", birth);
            }
            model.addAttribute("user", userMap);
        }
        return "system/user/user_edit";
    }

    /**
     * 用户详情
     * @param userId
     * @param model
     * @return
     */
    @RequestMapping(value = "/view/{userId}", method = RequestMethod.GET)
    @RequiresPermissions("user_view")
    public String viewUser(@PathVariable String userId, Model model) {
        WherePrams where = Method.where("id", C.EQ, userId);
        SysUser user = userService.get(where);
        if (user != null) {
            Map<String, Object> userMap = MapUtils.transBean2Map(user);
            String roleid = user.getRoleId();
            if (StringUtils.isNotBlank(roleid)) {
                //WherePrams role_where = Method.where("id", C.EQ, roleid);
                SysRole role = roleService.get(roleid);
                if (role != null) {
                    userMap.put("roleName", role.getName());
                } else {
                    userMap.put("roleName", "-");
                }
            }
            String officeId = user.getOfficeId();
            if (StringUtils.isNotEmpty(officeId)) {
                SysOffice office = officeService.get(officeId);
                if (null != office) {
                    userMap.put("officeName", office.getName());
                } else {
                    userMap.put("officeName", "-");
                }
            } else {
                userMap.put("officeName", "-");
            }
            String birthday = user.getBirthday();
            if (birthday != null) {
                String birth = DateUtil
                    .dateFormatToString(DateUtil.stringToDate(birthday), "yyyy-MM-dd");
                userMap.put("birthday", birth);
            }
            model.addAttribute("user", userMap);
        }
        return "system/user/user_detail";
    }

    /**
     * 保存添加
     */
    @RequestMapping(value = "/save/add", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("user_add")
    public Object saveUser(SysUser sysUser, HttpServletRequest req) throws Exception {
        if (sysUser == null) {
            return new ResultObj(1, "参数传递错误，新增用户失败", null);
        }
        WherePrams wherePrams = Method.where("status", C.EQ, "1");
        if (StringUtils.isEmpty(sysUser.getUserName())) {
            return new ResultObj(1, "参数传递错误，新增用户失败", null);
        }
        wherePrams.and("userName", C.EQ, sysUser.getUserName());
        SysUser user = userService.get(wherePrams);
        if (user != null) {
            return new ResultObj(1, "用户名已存在，新增用户失败", null);
        }
        sysUser.setStatus("1");
        sysUser.setSalt(ShiroKit.getRandomSalt(5));
        sysUser.setPassword(ShiroKit.md5(sysUser.getPassword(), sysUser.getSalt()));
        sysUser.setCreateDate(DateUtil.dateToString(new Date()));
        String flag = userService.addLocalByid(sysUser);
        //updateRedisUser();
        log.info("============保存成功===============");
        return new ResultObj(0, "保存成功", flag);
    }

    /**
     * 保存修改
     */
    @RequestMapping(value = "/save/update", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("user_edit")
    public Object saveUpdate(SysUser sysUser) throws Exception {
        if (sysUser == null) {
            return new ResultObj(1, "参数传递错误，修改用户失败", null);
        }
        WherePrams where = Method.where("status", C.EQ, "1");
        where.and("id", C.EQ, sysUser.getId());
        SysUser user2 = userService.get(where);
        if (user2 == null) {
            return new ResultObj(1, "根据用户Id未查询到用户信息，修改用户失败", null);
        }
        WherePrams wherePrams = Method.where("status", C.EQ, "1");
        if (StringUtils.isEmpty(sysUser.getUserName())) {
            return new ResultObj(1, "参数传递错误，新增用户失败", null);
        }
        wherePrams.and("userName", C.EQ, sysUser.getUserName());
        SysUser user = userService.get(wherePrams);
        if (user != null) {
            if (!user.getId().equals(sysUser.getId())) {
                return new ResultObj(1, "用户名已存在，修改用户失败", null);
            }
        }
        sysUser.setUpdateDate(DateUtil.dateToString(new Date()));

        //需要对保存的图片路径进行处理
        String filePath = sysUser.getAvatar();
        if (StringUtils.isNotEmpty(filePath) && filePath.indexOf(fileServerPath) != -1) {
            sysUser.setAvatar(filePath
                .substring(filePath.indexOf(fileServerPath) + fileServerPath.length(),
                    filePath.length()));
        }

        int flag = userService.updateLocal(sysUser);
        //updateRedisUser();
        return new ResultObj(0, "修改成功", flag);
    }

    /**
     * 保存系统用户信息
     * @param sysUser
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/save/reset", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("user_reset")
    public Object saveReset(SysUser sysUser) throws Exception {
        if (sysUser == null) {
            return new ResultObj(1, "参数传递错误，修改用户失败", null);
        }
        WherePrams where = Method.where("status", C.EQ, "1");
        where.and("id", C.EQ, sysUser.getId());
        SysUser user2 = userService.get(where);
        if (user2 == null) {
            return new ResultObj(1, "根据用户Id未查询到用户信息，修改用户失败", null);
        }
        //查看是否管理员，无法重置管理员密码
        String roleId = user2.getRoleId();
        if (StringUtils.isNotEmpty(roleId)) {
            SysRole role = roleService.get(roleId);
            if (role != null && role.getName().equals("admin")) {
                return new ResultObj(1, "无法重置管理员密码", null);
            }
        }
        sysUser.setPassword(ShiroKit.md5("111111", user2.getSalt()));
        sysUser.setUpdateDate(DateUtil.dateToString(new Date()));
        int flag = userService.updateLocal(sysUser);
        //updateRedisUser();
        return new ResultObj(0, "重置密码成功", flag);
    }

    /**
     * 重置密码页面
     * @return
     */
    @RequestMapping(value = "/user_chpwd", method = RequestMethod.GET)
    public String chpwd() {
        return "system/user/user_chpwd";
    }

    /**
     * 修改密码
     * @param oldPwd
     * @param newPwd
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/save/user_chpwd", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("user_edit")
    public Object saveChangePwd(@RequestParam String oldPwd, @RequestParam String newPwd)
        throws Exception {
		if(StringUtils.isEmpty(oldPwd)||StringUtils.isEmpty(newPwd)){
			return new ResultObj(1, "参数传递错误，修改密码失败", null);
		}
		//SysUser sysUser = (SysUser)redisService.getAttrAsObject(getRequest(), CommonConstant.SESSION_USER);
		 SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
		if(sysUser==null){
			return new ResultObj(1, "未查询到用户登录信息，修改密码失败", null);
		}
		if(!sysUser.getPassword().equals(ShiroKit.md5(oldPwd, sysUser.getSalt()))){
			return new ResultObj(1, "原密码错误，修改密码失败", null);
		}
		sysUser.setPassword(ShiroKit.md5(newPwd, sysUser.getSalt()));
		sysUser.setUpdateDate(DateUtil.dateToString(new Date()));
		int flag = userService.updateLocal(sysUser);
		//更新缓存信息
		//updateRedisUser();
		return new ResultObj(0, "成功", flag);
    }


    /**
     * 保存删除,逻辑删除
     */
    @RequestMapping(value = "/save/delete", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("mgr_delete")
    @Transactional
    public Object saveDelete(String ids) {
        if (!StringUtils.isNotEmpty(ids)) {
            return new ResultObj(1, "参数传递错误", null);
        }
        String[] list = ids.split(",");
        for (String id : list) {
            SysUser user2 = userService.get(id);
            //查看是否管理员，无法重置管理员密码
            String roleId = user2.getRoleId();
            if (StringUtils.isNotEmpty(roleId)) {
                SysRole role = roleService.get(roleId);
                if (role != null && role.getName().equals("admin") && user2.getUserName()
                    .equals("admin")) {
                    return new ResultObj(1, "无法删除管理员账号", null);
                }
            }
            WherePrams wherePrams = Method.where("id", C.EQ, id);
            SysUser user = new SysUser();
            user.setStatus("0");
            userService.updateLocal(user, wherePrams);
        }

        return new ResultObj(0, "删除成功", null);
        //return sysDeptService.del(deptId);
    }

    /**
     * 获取部门的tree列表
     */
    @RequestMapping(value = "/tree", method = RequestMethod.POST)
    @ResponseBody
    public List<ZTreeNode> tree(String officeId) {
    	SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        List<ZTreeNode> tree = sysDeptService.tree(officeId,sysUser);
        tree.add(ZTreeNode.createParent());
        return tree;
    }


    /**
     * 根据科室获取机构信息
     */
    @RequestMapping(value = "getOfficeByDept", method = RequestMethod.POST)
    @ResponseBody
    public Object getOfficeByDept(String deptId) throws Exception {
        //保存修改
        if (StringUtils.isEmpty(deptId)) {
            return new ResultObj(1, "参数传递异常", null);
        }
        WherePrams where = Method.where("id", C.EQ, deptId);
        SysDept dept = sysDeptService.get(where);
        if (dept != null) {
            SysOffice office = officeService.get(dept.getOfficeId());
            return office;
        }
        return new ResultObj(0, "成功", null);
    }

    @RequestMapping(value = "/save/changepwd", method = RequestMethod.GET)
    public String changePwd() {
        return "system/user/user_chpwd";
    }

    /**
     * 跳转到修改页面
     */
    @RequestMapping(value = "/user_info", method = RequestMethod.GET)
    @RequiresPermissions("user_edit")
    public String userInfo(Model model) {
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null) {
            return "login";
        }
        //从Shiro中获取的User信息有限，得根据userId到数据库去查询
        SysUser userInfo = userService.get(user.getId());
        if (userInfo != null) {
            Map<String, Object> userMap = MapUtils.transBean2Map(userInfo);
            String roleid = user.getRoleId();
            if (StringUtils.isNotBlank(roleid)) {
                //WherePrams role_where = Method.where("id", C.EQ, roleid);
                SysRole role = roleService.get(roleid);
                if (role != null) {
                    userMap.put("roleName", role.getName());
                } else {
                    userMap.put("roleName", "-");
                }
            } else {
                userMap.put("roleName", "-");
            }
            String deptid = user.getDeptId();
            if (StringUtils.isNotEmpty(deptid)) {
                SysDept dept = sysDeptService.get(deptid);
                if (dept != null) {
                    userMap.put("deptName", dept.getFullname());
                } else {
                    userMap.put("deptName", "-");
                }
            } else {
                userMap.put("deptName", "-");
            }
            String officeId = user.getOfficeId();
            if (StringUtils.isNotEmpty(officeId)) {
                SysOffice office = officeService.get(officeId);
                if (null != office) {
                    userMap.put("officeName", office.getName());
                } else {
                    userMap.put("officeName", "-");
                }
            } else {
                userMap.put("officeName", "-");
            }
            String birthday = user.getBirthday();
            if (birthday != null) {
                String birth = DateUtil
                    .dateFormatToString(DateUtil.stringToDate(birthday), "yyyy-MM-dd");
                userMap.put("birthday", birth);
            }
            String filePath = user.getAvatar();
            if (StringUtils.isNotEmpty(filePath)) {
                userMap.put("avatar", fileServerPath + filePath);
            }

            model.addAttribute("user", userMap);
        }

        return "system/user/user_view";
    }


    @Value("${img.location}")
    private String fileUploadPath;

    /**
     * 上传头像
     * @param request
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    @RequiresPermissions("file_upload")
    @ResponseBody
    @Transactional
    public Object upload(HttpServletRequest request, MultipartFile file) {
        try {

            //文件上传路径
            String serverPath = fileUploadPath;

            String uploadDir = "";

            //文件名称
            String fileName = file.getOriginalFilename();
            //文件后缀
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());

            uploadDir = uploadDir + "/" + "other" + "/" + "avator";

            //检查目录是否存在
            File dir = new File(serverPath + uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //随机名称
            String randomFileName = UUID.randomUUID().toString();
            //文件存在服务器上的路径
            String fileUrl = uploadDir + "/" + randomFileName + "." + suffix;

            //将文件上传到文集的物理地址
            File serverFile = new File(serverPath + fileUrl);
            file.transferTo(serverFile);
            log.info("文件上传成功");

            return new ResultObj(1, "文件上传成功", fileServerPath + fileUrl);

        } catch (Exception e) {
            log.error(e.getMessage());
            return new ResultObj(0, e.getMessage(), null);
        }

    }
    @Value("${path.path}")
    private String fileServerPath; 


}






